package com.aabte.permissionframeworklearn.permission.service;

import com.aabte.permissionframeworklearn.permission.beans.CacheKeyConstants;
import com.aabte.permissionframeworklearn.permission.util.JsonMapper;
import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.ShardedJedis;

/**
 * @author Daniel
 */
@Slf4j
@Service
public class SysCacheService {

    @Autowired
    private RedisPool redisPool;

    public void saveCache(String value, int timeoutSeconds, CacheKeyConstants prefix) {
        saveCache(value, timeoutSeconds, prefix, null);
    }

    public void saveCache(String value, int timeoutSeconds, CacheKeyConstants prefix, String... keys) {
        if (null == value) {
            return;
        }


        ShardedJedis instance = null;
        try {
            String cacheKey = generateCacheKey(prefix, keys);
            instance = redisPool.instance();
            instance.setex(cacheKey, timeoutSeconds, value);
        } catch (Exception e) {
            log.error("save cache exception, prefix: {}, keys: {}, value: {}",
                    prefix, JsonMapper.obj2String(keys), value, e);
        } finally {
            redisPool.safeClose(instance);
        }
    }

    public String getFromCache(CacheKeyConstants prefix, String... keys) {

        ShardedJedis instance = null;
        try {
            String cacheKey = generateCacheKey(prefix, keys);
            instance = redisPool.instance();
            return instance.get(cacheKey);
        } catch (Exception e) {
            log.error("get from cache exception. prefix: {}, keys: {}", prefix, JsonMapper.obj2String(keys), e);
        } finally {
            redisPool.safeClose(instance);
        }
        return null;
    }

    public String generateCacheKey(CacheKeyConstants prefix, String... keys) {
        String key = prefix.name();
        if (keys != null && keys.length > 0) {
            key += "_" + Joiner.on("_").join(keys);
        }
        return key;
    }

}
